import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// axios配置
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (!config.headers.Authorization && store.state.user.token) {
      config.headers.Authorization = store.state.user.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // const { data, message } = response
    // 返回得时候解构一下
    return response.data
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      // message: error.message || '请求拦截器报错了',
      message: '请求拦截器报错了',
      type: 'error'
      // duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
